//
//  YTFEmotionView.swift
//  sinaWeibo
//
//  Created by pro on 16/3/8.
//  Copyright © 2016年 pro. All rights reserved.
//

import UIKit

let YTFCollectionViewCellReuseID = "YTFCollectionViewCellReuseID"
let kNotificationEmotionTransform = "kNotificationEmotionTransform"

//遵循协议
class YTFEmotionView: UIView ,UICollectionViewDataSource,YTFToolBarViewDelegate{
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
        setupCollectionView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加控件并设置约束
    private func setupUI(){
        
        //添加视图
        addSubview(toolBar)
        addSubview(collectionView)
        
        //设置约束
        //底部视图
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.bottom.equalTo(self.snp_bottom)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        
        //上面的视图
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
    
    }
    
    
    private func setupCollectionView(){
        
        //设置数据源代理
        collectionView.dataSource = self
        
        //注册cell
        collectionView.registerClass(YTFEmotionCollectionViewCell.self, forCellWithReuseIdentifier: YTFCollectionViewCellReuseID)
        
        //百变滚动方向
        flowLayout.scrollDirection = .Horizontal
        
        //取消滚动条
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        
        //设置分页
        collectionView.pagingEnabled = true
        
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //设置cell大小
        flowLayout.itemSize = CGSizeMake(kUIScreenWidth, collectionView.bounds.height)
        
        //设置间距
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
    }
    
    
    //懒加载
    //底部视图
    private lazy var toolBar: YTFToolBarView = {
    
        let toolBar = YTFToolBarView()
        
        //设置代理
        toolBar.delegate = self
        
        return toolBar
    }()
    
    //上面的视图
    private lazy var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)

}

//MARK: -- YTFToolBarViewDelegate的代理方法
extension YTFEmotionView {
    
    func didToolBarItemClick(type: YTFEmotionToolBarType) {
        switch type {
            
        case .Rescent :
            let indexPath = NSIndexPath(forItem: 0, inSection: 0)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        case .Default :
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        case .Emoji :
            let indexPath = NSIndexPath(forItem: 0, inSection: 2)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        case .Lxh :
            let indexPath = NSIndexPath(forItem: 0, inSection: 3)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        default : break
        
        }
    }

}


//MARK: -- collectionView的数据源代理方法
extension YTFEmotionView {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return YTFEmotionManager.getAllEmotions().count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return YTFEmotionManager.getAllEmotions()[section].count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YTFCollectionViewCellReuseID, forIndexPath: indexPath) as! YTFEmotionCollectionViewCell
        
//        cell.textLabel.text = "第\(indexPath.section)部分，第\(indexPath.item)个cell"
        
        //赋值
        cell.emotions = YTFEmotionManager.getAllEmotions()[indexPath.section][indexPath.item]
        
        return cell
    }

}


//自定义cell
class YTFEmotionCollectionViewCell: UICollectionViewCell {
    
    //定义一个数组，用来存放重用的20个表情，在赋值的时候直接修改里面的值
    var emotions: [YTFEmotion]?{
        
        didSet{
            
            //为解决重用问题，遍历重用数组，隐藏响应button
            for (index,button) in reuseButtons.enumerate(){
                button.hidden = true
            }
            
            //遍历重用button的数组，对每一个button设置属性
            for (index,emotion) in emotions!.enumerate() {
                
                //根据索引，获取重用button数组中对应的button
                let button = reuseButtons[index]
                button.emotion = emotion
                
                                
            
            }
        
        }
        
    }
    
    //定义一个重用的按钮数组来接收重用的按钮
    private lazy var reuseButtons: [YTFEmotionButton] = [YTFEmotionButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件并设置约束
    private func setupUI(){
        
        backgroundColor = randomColor()
        
//        //添加控件
//        contentView.addSubview(textLabel)
//        
//        //添加约束
//        textLabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView.snp_center)
//        }
        addEmotions()
        
    }
    
    private func addEmotions(){
        
        //设置按钮的宽高
        let width = frame.size.width / 7
        let height = frame.size.height / 3
        
        //根据九宫格添加按钮
        for i in 0..<20 {
            
            let button = YTFEmotionButton(type: UIButtonType.Custom)
            
            //计算行数和列数
            let row = i / 7
            let col = i % 7
            
            //设置button的frame
            button.frame = CGRectMake(CGFloat(col)*width, CGFloat(row)*height, width, height)
            
            //设置内部文字颜色
            button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            
//            button.setTitle("\(i)", forState: UIControlState.Normal)
            //添加按钮点击事件
            button.addTarget(self, action: "emotionButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //添加到视图上
            contentView.addSubview(button)
            
            //添加到重用的button数组中
            reuseButtons.append(button)
        }
        
        //添加删除按钮并设置frame
        deleteButton.frame = CGRectMake(6*width, 2*height, width, height)
        contentView.addSubview(deleteButton)
        
    }
    
    //表情按钮点击事件
    @objc private func emotionButtonClick(button: YTFEmotionButton){
        
        //因为要回调给publishViewController，不是直接的对应关系，使用通知来回调
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEmotionTransform, object: nil, userInfo: ["emotion":button.emotion!])
        
//        print("表情被点击了")
        YTFEmotionManager.addRecentEmotions(button.emotion)
    
    }
    
    //删除按钮的点击事件
    @objc private func emotionDeleteClick(){
    
        print("删除")
    
    }
    
    //懒加载
    //删除按钮
    private lazy var deleteButton: YTFEmotionButton = {
        
        let button = YTFEmotionButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Normal)
        
        button.addTarget(self, action: "emotionDeleteClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    private lazy var textLabel: UILabel = {
        
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(15)
        
        return label
    
    }()
    
}


